from rest_framework.authentication import BaseAuthentication
from datetime import datetime, timedelta
from django.core.cache import cache
from Rufe.models import UserToken
from rest_framework.exceptions import AuthenticationFailed


# 自定义认证
class MyAuthentication(BaseAuthentication):

    def authenticate(self, request):
        # 将token放入请求头中
        token = request.META.get('HTTP_AUTHENTICATION')
        # token = request.query_params.get("token")
        user = cache.get(token)
        if user:
            return user, token
        token_obj = UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise AuthenticationFailed('认证失败')

        created_time = token_obj.createdate
        now_time = datetime.now()
        delta = now_time - created_time

        if delta < timedelta(seconds=5):
            remain_time = timedelta(weeks=2) - delta
            cache.set(token_obj.token, token_obj.user, min(remain_time.total_seconds(), 3600*24*7))
            return token_obj.user, token
        else:
            raise AuthenticationFailed('认证超时')
